const {getFileMd5} = require('./createMd5')
const {copyDir} = require('./fs')
const fs = require('fs')
const path = require('path')
const loopPrimaryDirs = (dir, arr,nodeDiffDirectory,nodeDiffFile) => {
	// 获取文件夹
	let files = fs.readdirSync(dir)
	// 遍历当前文件夹下所有文件
	for (let file of files) {
		let fullpath = path.join(dir, file)
		// 获取文件
		let stat = fs.statSync(fullpath)
		if (stat.isFile()) {
			if(!nodeDiffFile.includes(file)){
				arr.push(fullpath)
			}
			
		} else if (stat.isDirectory()) {
			if(!nodeDiffDirectory.includes(file)){
				arr.push(fullpath)
			}
			
		}
	}
}
/**
 * 循环遍历本地文件夹
 * @param dir 用于diff文件夹路径
 * @param oldPath 用于diff的项目根路径
 * @param newPath 被diff的项目根路径
 * @returns {}
 */
const diffDirs = (dir,oldPath,newPath,ignoreDiffDirectory,ignoreDiffFile) => {
	// 获取文件
	let stat = fs.statSync(dir)
	let remoteFullpath = dir.replace(oldPath,newPath)
	// 判断文件是文件还是文件夹
	if (stat.isFile()) {
		// 判断文件是否无需diff
		if(!ignoreDiffFile.includes(remoteFullpath)){
			// diff文件的内容
			let content = fs.readFileSync(dir).toString()
			try {
				// 获取待diff的文件，判断是否存在
				fs.accessSync(remoteFullpath, fs.constants.F_OK)
				let remoteStat = fs.statSync(remoteFullpath)
				
				// 存在则对比两个文件是否一致，不一致则将被diff的文件内容替换为用于diff的文件内容
				if(getFileMd5(dir) !== getFileMd5(remoteFullpath)){
					
					fs.unlinkSync(remoteFullpath)
					fs.copyFileSync(dir, remoteFullpath)
				}
			} catch (e) {
				fs.copyFileSync(dir, remoteFullpath)
			}
		}
	
	} else if (stat.isDirectory()) {
		try {
			// 获取待diff的文件，判断是否存在
			fs.accessSync(remoteFullpath, fs.constants.F_OK)
			// 判断文件夹是否无需diff
			if(!ignoreDiffDirectory.includes(remoteFullpath)){
				// 获取文件夹
				let files = fs.readdirSync(dir)
				for (let file of files) {
					let fullpath = path.join(dir, file)
					diffDirs(fullpath,oldPath,newPath,ignoreDiffDirectory,ignoreDiffFile)
				}
				
			}
		} catch (e) {
			console.log(`正在将${dir}下的文件复制至当前项目`)
			copyDir(dir,remoteFullpath)
		}

		
	}
}

module.exports = {loopPrimaryDirs,diffDirs}